package leetcode.lcp0003;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public boolean robot(String command, int[][] obstacles, int x, int y) {
		char[] cmd = command.toCharArray();
		int len = cmd.length;
		int up = 0, right = 0;
		for (int i = 0; i < len; i++) {
			if (cmd[i] == 'U') {
				up++;
			} else {
				right++;
			}
		}
		if (up == 0) {// 只有向右走的,y==0的都能到（无挡情况）
			if (y != 0) {
				return false;
			} else {
				for (int[] obs : obstacles) {
					if (obs[1] == 0) {
						return false;
					}
				}
				return true;
			}
		}
		if (right == 0) {// 只有向上走的,x==0的都能到（无挡情况）
			if (x != 0) {
				return false;
			} else {
				for (int[] obs : obstacles) {
					if (obs[0] == 0) {
						return false;
					}
				}
				return true;
			}
		}
		int posx = right, posy = up;
		List<int[]>[][] group = new ArrayList[len][len];
		for (int i = 0; i < len; i++) {
			int startx = posx % right, starty = posy % up;
			if (group[startx][starty] == null) {
				group[startx][starty] = new ArrayList<>();
			}
			group[startx][starty].add(new int[] { posx, posy });
			if (cmd[i] == 'U') {
				posy++;
			} else {
				posx++;
			}
		}
		for (int[] cur : obstacles) {
			if (cur[0] > x || cur[1] > y) {
				continue;
			}
			if (this.avaliable(cur[0], cur[1], group, up, right)) {
				return false;
			}
		}
		return this.avaliable(x, y, group, up, right);
	}

	// x,y是不是group上以[right,up]为周期的点
	private boolean avaliable(int x, int y, List<int[]>[][] group, int up, int right) {
		int startx = x % right, starty = y % up;
		List<int[]> list = group[startx][starty];
		if (list == null) {
			return false;
		}
		for (int[] cur : list) {
			if ((x - cur[0]) * up == (y - cur[1]) * right) {
				return true;
			}
		}
		return false;
	}


	@Override
	public void debug4() {
		HelpDebug.compare(true, this.robot("URR", HelpDebug.str2array1("[]"), 3, 2));
		HelpDebug.compare(false, this.robot("URR", HelpDebug.str2array1("[[2,2]]"), 3, 2));
		HelpDebug.compare(true, this.robot("URR", HelpDebug.str2array1("[[4,2]]"), 3, 2));
		HelpDebug.compare(true, this.robot("URRURRR", HelpDebug.str2array1("[[7,7],[0,5],[2,7],[8,6],[8,7],[6,5],[4,4],[0,3],[3,6]]"),
				4915, 1966));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		int x = 9;
		System.out.println(4%-3);
	}

}
